package com.isoft.service.impl;

import com.isoft.entity.DfmeSflgEntity;
import com.isoft.mapper.DfmeSflgMapper;
import com.isoft.mapper.DfmeSflgMapper.SharedFlightDto;
import com.isoft.service.DfmeSflgService;
import com.isoft.util.XmlParserUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DfmeSflgServiceImpl implements DfmeSflgService {
    private static final Logger logger = LoggerFactory.getLogger(DfmeSflgServiceImpl.class);

    @Autowired
    private DfmeSflgMapper dfmeSflgMapper;

    @Autowired
    private XmlParserUtil xmlParserUtil;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String parseAndSave(MultipartFile file) throws IOException {
        String xmlContent = new String(file.getBytes(), StandardCharsets.UTF_8);
        logger.info("Processing XML file: {}, size: {} bytes",
                file.getOriginalFilename(), file.getSize());
        return parseAndSave(xmlContent);
    }

    @Override
    public void parseAndSave(DfmeSflgEntity entity) {
        processFlightData(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String parseAndSave(String xmlContent) {
        try {
            if (xmlContent == null || xmlContent.trim().isEmpty()) {
                throw new IllegalArgumentException("XML content is empty");
            }

            DfmeSflgEntity entity = xmlParserUtil.parseXml(xmlContent, DfmeSflgEntity.class);

            if (entity == null || entity.getDflt() == null || entity.getDflt().getSflg() == null) {
                throw new IllegalArgumentException("Invalid XML structure");
            }

            processFlightData(entity);

            return "Shared flight data processed successfully. Flight ID: " + entity.getDflt().getFlightId();
        } catch (Exception e) {
            logger.error("XML processing failed", e);
            throw new RuntimeException("Failed to process XML: " + e.getMessage());
        }
    }

    private void processFlightData(DfmeSflgEntity entity) {
        // 调试：插入前打印meta各字段
        if (entity.getMeta() != null) {
            logger.debug("meta.sender: {}", entity.getMeta().getSender());
            logger.debug("meta.receiver: {}", entity.getMeta().getReceiver());
            logger.debug("meta.type: {}", entity.getMeta().getType());
            logger.debug("meta.subType: {}", entity.getMeta().getSubType());
            logger.debug("meta.dateTime: {} 类型: {}", entity.getMeta().getDateTime(), entity.getMeta().getDateTime() != null ? entity.getMeta().getDateTime().getClass().getName() : "null");
        } else {
            logger.debug("meta为null");
        }
        // 插入元数据
        dfmeSflgMapper.insertMeta(entity);

        // 插入航班基础信息
        dfmeSflgMapper.insertFlightBase(entity);

        // 准备共享航班数据
        List<SharedFlightDto> sharedFlights = entity.getDflt().getSflg().getSflts().stream()
                .map(sflt -> {
                    SharedFlightDto dto = new SharedFlightDto();
                    dto.setFlightId(entity.getDflt().getFlightId());
                    dto.setAirlineCode(sflt.getAirlineCode());
                    dto.setFlightNumber(sflt.getFlightNumber());
                    return dto;
                })
                .collect(Collectors.toList());

        // 批量插入共享航班
        int result = dfmeSflgMapper.batchInsertSharedFlights(sharedFlights);
        logger.info("Inserted {} shared flight records for flight ID: {}",
                result,
                entity.getDflt().getFlightId());
    }
}